import React, { useState, useEffect } from 'react';
import {
  Select,
  Space,
  Button,
  Modal,
  Input,
  Tag,
  Tooltip,
  Card,
  Row,
  Col,
  Badge,
  message
} from 'antd';
import {
  EditOutlined,
  PlusOutlined,
  StarOutlined,
  StarFilled,
  ThunderboltOutlined,
  EyeOutlined,
  ClockCircleOutlined,
  FireOutlined,
  RobotOutlined
} from '@ant-design/icons';
import { PromptTemplate } from '@/types/prompt';
import { useConversationStore } from '@/stores/conversation.store';
import { usePromptStore } from '@/stores/prompt.store';
import './style.css';

const { Option } = Select;
const { Search } = Input;

interface PromptSelectorProps {
  onSelect?: (template: PromptTemplate) => void;
  onPreview?: (template: PromptTemplate) => void;
  showQuickActions?: boolean;
  className?: string;
}

const PromptSelector: React.FC<PromptSelectorProps> = ({
  onSelect,
  onPreview,
  showQuickActions = true,
  className = ''
}) => {
  const {
    currentPromptId,
    currentPromptTemplate,
    setPromptTemplate,
    switchPromptWithoutInterrupt
  } = useConversationStore();
  
  const {
    prompts = [],
    recentPrompts = [],
    favoritePrompts = [],
    loadPrompts,
    toggleFavorite
  } = usePromptStore();
  
  const [searchValue, setSearchValue] = useState('');
  const [filterCategory, setFilterCategory] = useState<string>('all');
  const [showLibraryModal, setShowLibraryModal] = useState(false);
  const [previewTemplate, setPreviewTemplate] = useState<PromptTemplate | null>(null);
  
  useEffect(() => {
    loadPrompts();
  }, []);
  
  // 过滤提示词
  const filteredPrompts = (prompts || []).filter(prompt => {
    const matchesSearch = !searchValue || 
      prompt.name.toLowerCase().includes(searchValue.toLowerCase()) ||
      prompt.description?.toLowerCase().includes(searchValue.toLowerCase());
    
    const matchesCategory = filterCategory === 'all' || prompt.category === filterCategory;
    
    return matchesSearch && matchesCategory;
  });
  
  // 处理选择
  const handleSelect = (promptId: string) => {
    const template = prompts.find(p => p.id === promptId);
    if (template) {
      setPromptTemplate(template);
      if (onSelect) {
        onSelect(template);
      }
      message.success(`已切换到提示词: ${template.name}`);
    }
  };
  
  // 处理快速切换
  const handleQuickSwitch = (template: PromptTemplate) => {
    switchPromptWithoutInterrupt(template);
    message.success(`已无缝切换到提示词: ${template.name}`);
  };
  
  // 处理预览
  const handlePreview = (template: PromptTemplate) => {
    setPreviewTemplate(template);
    if (onPreview) {
      onPreview(template);
    }
  };
  
  // 渲染提示词选项
  const renderPromptOption = (prompt: PromptTemplate) => {
    const isCurrent = prompt.id === currentPromptId;
    const isFavorite = favoritePrompts.includes(prompt.id);
    const isRecent = recentPrompts.includes(prompt.id);
    
    return (
      <Option key={prompt.id} value={prompt.id}>
        <div className="prompt-option">
          <Space>
            {isCurrent && <Badge status="processing" />}
            <span className="prompt-name">{prompt.name}</span>
            {isFavorite && <StarFilled style={{ color: '#faad14' }} />}
            {isRecent && <ClockCircleOutlined style={{ color: '#1890ff' }} />}
            {prompt.usageCount > 100 && <FireOutlined style={{ color: '#ff4d4f' }} />}
          </Space>
          <div className="prompt-meta">
            <Tag color="blue" style={{ fontSize: 10 }}>{prompt.category}</Tag>
            <span className="usage-count">使用 {prompt.usageCount} 次</span>
          </div>
        </div>
      </Option>
    );
  };
  
  // 渲染快捷操作
  const renderQuickActions = () => {
    if (!showQuickActions) return null;
    
    return (
      <Space className="prompt-quick-actions">
        <Tooltip title="打开提示词库">
          <Button
            icon={<RobotOutlined />}
            onClick={() => setShowLibraryModal(true)}
          />
        </Tooltip>
        {currentPromptTemplate && (
          <>
            <Tooltip title="编辑当前提示词">
              <Button icon={<EditOutlined />} />
            </Tooltip>
            <Tooltip title="预览效果">
              <Button
                icon={<EyeOutlined />}
                onClick={() => handlePreview(currentPromptTemplate)}
              />
            </Tooltip>
            <Tooltip title={favoritePrompts.includes(currentPromptId!) ? '取消收藏' : '收藏'}>
              <Button
                icon={favoritePrompts.includes(currentPromptId!) ? <StarFilled /> : <StarOutlined />}
                onClick={() => toggleFavorite(currentPromptId!)}
              />
            </Tooltip>
          </>
        )}
        <Tooltip title="创建新提示词">
          <Button type="primary" icon={<PlusOutlined />} />
        </Tooltip>
      </Space>
    );
  };
  
  return (
    <div className={`prompt-selector ${className}`}>
      <Space>
        <Select
          style={{ width: 250 }}
          placeholder="选择提示词"
          value={currentPromptId}
          onChange={handleSelect}
          showSearch
          filterOption={(input, option) => {
            const prompt = prompts.find(p => p.id === option?.value);
            return prompt?.name.toLowerCase().includes(input.toLowerCase()) || false;
          }}
        >
          {/* 收藏的提示词 */}
          {favoritePrompts && favoritePrompts.length > 0 && (
            <Select.OptGroup label="收藏">
              {prompts
                .filter(p => favoritePrompts.includes(p.id))
                .map(renderPromptOption)}
            </Select.OptGroup>
          )}
          
          {/* 最近使用 */}
          {recentPrompts && recentPrompts.length > 0 && (
            <Select.OptGroup label="最近使用">
              {recentPrompts
                .slice(0, 5)
                .map(id => prompts.find(p => p.id === id))
                .filter(Boolean)
                .map(renderPromptOption)}
            </Select.OptGroup>
          )}
          
          {/* 所有提示词 */}
          <Select.OptGroup label="所有提示词">
            {filteredPrompts.map(renderPromptOption)}
          </Select.OptGroup>
        </Select>
        
        {renderQuickActions()}
      </Space>
      
      {/* 提示词库Modal */}
      <Modal
        title="提示词库"
        open={showLibraryModal}
        onCancel={() => setShowLibraryModal(false)}
        width={900}
        footer={null}
      >
        <Space direction="vertical" style={{ width: '100%' }} size={16}>
          <Row gutter={16}>
            <Col span={16}>
              <Search
                placeholder="搜索提示词"
                value={searchValue}
                onChange={e => setSearchValue(e.target.value)}
                allowClear
              />
            </Col>
            <Col span={8}>
              <Select
                style={{ width: '100%' }}
                value={filterCategory}
                onChange={setFilterCategory}
              >
                <Option value="all">全部类别</Option>
                <Option value="role">角色扮演</Option>
                <Option value="style">写作风格</Option>
                <Option value="domain">专业领域</Option>
                <Option value="custom">自定义</Option>
              </Select>
            </Col>
          </Row>
          
          <div className="prompt-grid">
            <Row gutter={[16, 16]}>
              {filteredPrompts.map(prompt => (
                <Col key={prompt.id} xs={24} sm={12} md={8}>
                  <Card
                    className="prompt-card"
                    hoverable
                    actions={[
                      <Button
                        type="text"
                        icon={<ThunderboltOutlined />}
                        onClick={() => handleQuickSwitch(prompt)}
                      >
                        使用
                      </Button>,
                      <Button
                        type="text"
                        icon={<EyeOutlined />}
                        onClick={() => handlePreview(prompt)}
                      >
                        预览
                      </Button>
                    ]}
                  >
                    <Card.Meta
                      title={
                        <Space>
                          {prompt.name}
                          {favoritePrompts.includes(prompt.id) && (
                            <StarFilled style={{ color: '#faad14' }} />
                          )}
                        </Space>
                      }
                      description={prompt.description}
                    />
                    <div className="prompt-card-footer">
                      <Tag color="blue">{prompt.category}</Tag>
                      <span className="usage-text">
                        <FireOutlined /> {prompt.usageCount}
                      </span>
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          </div>
        </Space>
      </Modal>
      
      {/* 预览Modal */}
      {previewTemplate && (
        <Modal
          title={`预览: ${previewTemplate.name}`}
          open={!!previewTemplate}
          onCancel={() => setPreviewTemplate(null)}
          footer={[
            <Button key="use" type="primary" onClick={() => {
              handleSelect(previewTemplate.id);
              setPreviewTemplate(null);
            }}>
              使用此提示词
            </Button>
          ]}
          width={700}
        >
          <Space direction="vertical" style={{ width: '100%' }} size={16}>
            <Card size="small">
              <p><strong>描述：</strong>{previewTemplate.description}</p>
              <p><strong>类别：</strong><Tag color="blue">{previewTemplate.category}</Tag></p>
              <p><strong>使用次数：</strong>{previewTemplate.usageCount}</p>
            </Card>
            
            {previewTemplate.systemPrompt && (
              <Card size="small" title="系统提示词">
                <pre className="prompt-preview-content">
                  {previewTemplate.systemPrompt}
                </pre>
              </Card>
            )}
            
            {previewTemplate.userPromptPrefix && (
              <Card size="small" title="用户提示词前缀">
                <pre className="prompt-preview-content">
                  {previewTemplate.userPromptPrefix}
                </pre>
              </Card>
            )}
            
            {previewTemplate.variables && previewTemplate.variables.length > 0 && (
              <Card size="small" title="变量">
                <Space wrap>
                  {previewTemplate.variables.map(variable => (
                    <Tag key={variable.name} color="green">
                      {variable.name}
                      {variable.required && <span style={{ color: 'red' }}>*</span>}
                    </Tag>
                  ))}
                </Space>
              </Card>
            )}
          </Space>
        </Modal>
      )}
    </div>
  );
};

export default PromptSelector;